/**
 * SpringMVC restful 风格
 * 用户控制器，控制关于线下支付的一些业务逻辑操作
 * @author WangXinLei
 * @date 2014-11-18
 */
package com.chnbst.bstyun.controller.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.core.common.Pager;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.eos.CreateNum;
import com.chnbst.bstyun.eos.Eos;
import com.chnbst.bstyun.model.pojo.Cashflow;
import com.chnbst.bstyun.model.pojo.Deal;
import com.chnbst.bstyun.model.pojo.Product;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.vo.OrderVo;
import com.chnbst.bstyun.service.CashflowService;
import com.chnbst.bstyun.service.DealService;
import com.chnbst.bstyun.service.MealService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.ProductService;
import com.chnbst.bstyun.service.UserService;

/**
 * 控制器注解 请求映射注解
 * controller 代表类是控制器
 * restcontroller 代表类是控制器， 所有的方法 都是ajax方法
 * @author 
 *
 */
@Controller
@RequestMapping("/order")
public class OrderAdminController {
	//每页显示的用户数
	private int pageSize = 10;
	//用户列表页码
	private int currPage = 1;
	/**
	 * 注入 业务逻辑层
	 */
	@Autowired
	private MealService mealService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private UserService userService;
	@Autowired
	private ProductService productService;
	@Autowired 
	private CreateNum createNum;
	@Autowired
	private CashflowService cashflowService;
	@Autowired
	private DealService dealService;
	@Autowired
	private Eos eos;
	
	/**
	 * @return 订单列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/orderList",method=RequestMethod.GET)
	public ModelAndView orderList()throws Exception{
		return new ModelAndView("admin/financeManager/orderManager");
	}
	
	/**
	 * Ajax 分页查询订单列表list
	 * @return 订单列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/orderList/search",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> orderList(String page,String last)throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(SignUtil.isNotEmpty(page)) {
			currPage = Integer.valueOf(page);
		}
		if(SignUtil.isNotEmpty(last)) {
			pageSize = Integer.valueOf(last);
		}
		
		int totalRows = orderService.selectOrderCount(map);
		int pageCount = Pager.getPageCount(totalRows, pageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, pageSize);
		map.put("start", start);
		map.put("pageSize", pageSize);
		map.put("sortField", "order_id");
		map.put("sortOrder", "desc");
		
		List<OrderVo> orderList = orderService.selectAllOrders(map);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("page", currPage);
		resultMap.put("pageCount", pageCount);
		resultMap.put("totalRows", totalRows);
		resultMap.put("orderList", orderList);
		
		return resultMap;
	}

	/**
	 * 根据order_id单条数据的详细信息
	 * @return 订单列表详情页面
	 * @throws Exception
	 */
	@RequestMapping(value="/orderDetail/{orderId}",method=RequestMethod.GET)
	public ModelAndView orderDetail(@PathVariable Integer orderId)throws Exception{
		
		ModelAndView mav = new ModelAndView();
		//加载订单列表的详细信息
		OrderVo orderInfo = orderService.selectOrderDetailByOrderId(orderId);
		if(!orderInfo.getProIds().equals("") && orderInfo.getProIds() != null){
			String proIds = orderInfo.getProIds(); 
			String str[] = proIds.split("\\|");
			
			List<Product> pList = new ArrayList<Product>();
			
			for (int i = 0; i < str.length; i++) {
				Product product = productService.selectProductByProductId(Integer.valueOf(str[i]));
				pList.add(product);
			}
			mav.addObject("pList", pList);
		}else{
			mav.addObject("pList", null);
		}
		mav.addObject("orderInfo", orderInfo);
		mav.setViewName("admin/financeManager/orderDetail");
		return mav;
	}
	
	/**
	 * 根据ID和按钮id修改订单列表的状态
	 * @return true 或者false
	 * @throws Exception
	 */
	@RequestMapping(value="/updateOrder",method=RequestMethod.POST)
	@ResponseBody
	public boolean updateOrder(HttpServletRequest request,Integer orderId) throws Exception{
		OrderVo order = orderService.selectOrderDetailByOrderId(orderId);
		
		order.setOrderState("2");
		//修改订单状态
		boolean a = orderService.updateOrderByOrderId(order);
		
		User userInfo = userService.selectUserInfoByUserId(order.getUserId());
		User baseUser = userService.selectUserInfoByUserId(order.getParentId());
		baseUser.setAccountMoney(baseUser.getAccountMoney()+order.getPayMoney());
		//该余额冻结，目前还没有冻结功能
		baseUser.setInvoiceMoney(baseUser.getInvoiceMoney()-order.getPayMoney());
		String domain = userInfo.getCompanyDomainName();
		
		//修改user表中的账户余额
		boolean b = userService.updateAccountMoneyByUserId(baseUser);
		
		//新增现金收支明细数据
		Cashflow cashflow = new Cashflow();
		cashflow.setCashflowNum(createNum.createCashflowNum("2"));
		cashflow.setUserId(order.getParentId());
		cashflow.setOrderId(order.getOrderId());
		cashflow.setDealType(1);
		cashflow.setCreateTime(new Date());
		cashflow.setDisburseMoney(0.00);
		cashflow.setIncomeMoney(order.getPayMoney());
		cashflow.setThenAccount(baseUser.getAccountMoney());
		//支付方式没有确定
		cashflow.setPayWayId(2);
		cashflow.setIsCancel(1);
		
		boolean c = cashflowService.insertCashflow(cashflow);
		
		String dealName = order.getMealName();
		if(dealName.equals("") || dealName == null) dealName = order.getProductName();
		Deal deal = new Deal();
		deal.setDealDate(new Date());
		deal.setDealName(dealName+" -- 退款");
		deal.setDealNum(order.getOrderNum());
		deal.setDealState("4");
		deal.setDisburseMoney(0.00);
		deal.setIncomeMoney(order.getPayMoney());
		deal.setPayWayId(2);
		deal.setUserId(order.getUserId());
		deal.setParentId(order.getParentId());
		deal.setIsCancel(1);
		boolean d = dealService.insertDeal(deal);
		
		if(order.getNewProId() == null){
			/*userInfo.setCompanyDomainName("");
			userInfo.setBelongCompanyName("");
			userInfo.setCompanyIndustryId(null);
			userInfo.setCompanyPosition("");
			userInfo.setContactName("");
			userInfo.setCompanyScaleId(null);
			userInfo.setIsYun("1");
			userInfo.setParentId(null);
			userInfo.setLoginNumber("0");
			userInfo.setRoleId(1);
			userInfo.setUserMessageNum(0);*/
			userInfo.setUserValid("1");
			userService.updateUserByKey(userInfo);
			
			eos.chargeBack(domain);
		}
		
		if(a && b && c && d)return true;
		return false;
	}
}
